package com.hitqz.robot.camera.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * 通用TCP客户端
 */
@Slf4j
public class TcpClient {

    private final String name;
    private final String host;
    private final Integer port;
    private final EventLoopGroup workerGroup;
    private final ChannelInitializer<Channel> channelInitializer;
    private Channel channel;

    // 构造函数，允许传递host、端口和ChannelInitializer
    public TcpClient(String name, String host, Integer port, ChannelInitializer<Channel> channelInitializer) {
        this.name = name;
        this.host = host;
        this.port = port;
        this.channelInitializer = channelInitializer;
        this.workerGroup = new NioEventLoopGroup();
    }

    public void connect() throws InterruptedException {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_RCVBUF, 1024 * 4)
                .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(1024, 2048, 1024 * 1024))
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true) // 启用 TCP 保活
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //断线重连处理器
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                log.warn("[tcp-client][{}] Channel connection inactive: {} reconnect...", name, ctx.channel().remoteAddress());
                                ctx.channel().eventLoop().schedule(TcpClient.this::connectAsync, 2, TimeUnit.SECONDS); // 5秒后重连
                                super.channelInactive(ctx);
                            }
                        });
                        //添加自定义的处理器
                        ch.pipeline().addLast(channelInitializer);
                    }
                });

        try {
            // 连接到服务器
            ChannelFuture f = b.connect(new InetSocketAddress(host, port)).sync();
            channel = f.channel();
            // 阻塞直到客户端通道关闭
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("[tcp-client][{}] connect {}:{} error", name, host, port, e);
        } finally {
            shutdown();
        }
    }

    public void connectAsync() {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_RCVBUF, 1024 * 4)
                .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(1024, 2048, 1024 * 1024))
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true) // 启用 TCP 保活
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //断线重连处理器
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                log.warn("[tcp-client][{}] Channel connection inactive: {} reconnect...", name, ctx.channel().remoteAddress());
                                ctx.channel().eventLoop().schedule(TcpClient.this::connectAsync, 3, TimeUnit.SECONDS); // 5秒后重连
                                super.channelInactive(ctx);
                            }
                        });
                        //添加自定义的处理器
                        ch.pipeline().addLast(channelInitializer);
                    }
                });

        b.connect(new InetSocketAddress(host, port)).addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                log.info("[tcp-client][{}] Connected to {}:{}", name, host, port);
                channel = future.channel();
            } else {
                log.error("[tcp-client][{}] Failed to connect to {}:{}", name, host, port, future.cause());
                future.channel().eventLoop().schedule(this::connectAsync, 3, TimeUnit.SECONDS); // 5秒后重连
            }
        });
    }

    public void shutdown() throws InterruptedException {
        if (channel != null) {
            channel.flush();
            channel.close().sync();
        }
        workerGroup.shutdownGracefully().sync();
        log.warn("[tcp-client][{}] shutdown gracefully!", name);
    }

    public boolean isConnected() {
        return channel != null && channel.isActive();
    }

    public void sendText(String message) {
        if (isConnected()) {
            channel.writeAndFlush(message);
        } else {
            log.info("[tcp-client][{}] Channel is not active, cannot send message", name);
        }
    }

    public void sendBinary(byte[] data) {
        if (isConnected()) {
            channel.writeAndFlush(data);
        } else {
            log.info("[tcp-client][{}] Channel is not active, cannot send message", name);
        }
    }

    public void sendObject(Object data) {
        if (isConnected()) {
            channel.writeAndFlush(data);
        } else {
            log.info("[tcp-client][{}] Channel is not active, cannot send message", name);
        }
    }

    public String getHost() {
        return host;
    }

    public Integer getPort() {
        return port;
    }
}
